package com.baymax.test.scene

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.ViewTreeObserver
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import com.airbnb.mvrx.Mavericks
import com.airbnb.mvrx.MavericksViewModelConfigFactory
import com.baymax.test.scene.life.LifeLogger
import com.bytedance.scene.NavigationSceneUtility
import com.bytedance.scene.SceneDelegate
import kotlinx.coroutines.Dispatchers
import kotlin.properties.Delegates

class MainActivity : AppCompatActivity(), ViewTreeObserver.OnGlobalFocusChangeListener {

    var delegate: SceneDelegate by Delegates.notNull()

    private val handler: Handler = Handler(Looper.getMainLooper())
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Mavericks.initialize(
            this, viewModelConfigFactory = MavericksViewModelConfigFactory(
                debugMode = BuildConfig.DEBUG,
                storeContextOverride = Dispatchers.IO
            )
        )
//        Fresco.initialize(this)
        lifecycle.addObserver(LifeLogger)
        Thread.setDefaultUncaughtExceptionHandler { t, e ->
            Log.e("MainActivity", "setDefaultUncaughtExceptionHandler in $t", e)
        }
//        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        window.decorView.viewTreeObserver.addOnGlobalFocusChangeListener(this)
        println("extra ${intent.extras}")
        println("extra ${intent.extras?.keySet()?.joinToString()}")
        dumpClassLoader()
        delegate = NavigationSceneUtility.setupWithActivity(this, ProjectTestScene::class.java)
            .rootSceneComponentFactory { classLoader, s, bundle ->
                Log.d("MAIN", "rootScene $s ,$bundle")
                ProjectTestScene().apply { setArguments(bundle ?: bundleOf()) }
            }
            .supportRestore(false)
            .drawWindowBackground(true)
            .fixSceneWindowBackgroundEnabled(true)
            .rootSceneArguments(intent.extras)
            .sceneBackground(R.color.white)
            .build()

    }

    fun dumpClassLoader() {
        var c = this.classLoader
        var count = 1
        while (c != null) {
            println("classLoader $count : $c")
            c= c.parent
            count += 1

        }
    }

    override fun onPostResume() {
        super.onPostResume()
        window.decorView.postDelayed({
            enableEdgeToEdge()
        } ,1000)
    }

    override fun onBackPressed() {
        if (!delegate.onBackPressed()) {
            super.onBackPressed()
        }
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        println("onWindowFocusChanged $hasFocus")
    }

    override fun onGlobalFocusChanged(oldFocus: View?, newFocus: View?) {
        println("onGlobalFocusChanged oldFocus $oldFocus")
        println("onGlobalFocusChanged newFocus $newFocus")
    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        println("dispatchKeyEvent event $event")
        if (event?.keyCode == KeyEvent.KEYCODE_MENU) {
            println("dispatchKeyEvent KEYCODE_MENU $event")
            startActivity(Intent(Settings.ACTION_SETTINGS))
        }
        return super.dispatchKeyEvent(event)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        println("onNewIntent ${intent.toUri(0)}")
    }

}